<?php
namespace app\admin\Controller;

use app\Admin\model\Article as ArticleModel;
use think\Controller;
use think\Db;

class Article extends Controller {

	public function add() 
	{
		if(request()->isPost()) 
		{
			$data = [
				'title'    		=> input('title'),
				'author'   		=> input('author'),
				'desc'     		=> input('desc'),
				'content'  		=> input('content'),
				'cateid'   		=> input('cateid'),
				'createtime'	=> input('createtime'),

			];
			if (input('status') == 'on') {
				$data['status'] = 1;
			}
			if($_FILES['pic']['tmp_name']){
                $file = request()->file('pic');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                $data['pic']='/uploads/'.$info->getSaveName();
        	}
            $validate = \think\Loader::validate('Article');
			if (!$validate->scene('edit')->check($data))	{
				$this->error($validate->getError());
				die;
			}
			if (db('Article')->insert($data))	{
				$this->success('添加文章成功！','Articlelist');
			}	else 	{
				$this->error('添加文章失败 !','add');
			}
			return;
		}	
			$cateres=db('cate')->select();
       	 	$this->assign('cateres',$cateres);
			return $this->fetch();
	}	

	public function watch()	{
		$id = input('id');
		$articles = db('article')->find($id);
		$this->assign(articles, $articles);

	}

    public function edit()
    {
    	$id 	  = input('id');
    	$articles = db('Article')->find($id);
    	if(request()->isPost()) {
    		$data=[
    			'id'		=> input('id'),
                'title'		=> input('title'),
                'author'	=> input('author'),
                'desc'		=> input('desc'),
                'content'	=> input('content'),
                'cateid'	=> input('cateid'),
    		];
            if(input('status') == 'on') {
                $data['status'] = 1;
            }	else {
                $data['status'] = 0;
            }
            if($_FILES['pic']['tmp_name'])	{		
                
                $file = request()->file('pic');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                $data['pic']='/uploads/'.$info->getSaveName();
            }
			$validate = \think\Loader::validate('Article');
    		if(!$validate->scene('edit')->check($data))
    		{
			   $this->error($validate->getError());
			   die;
			}
    		if(db('Article')->update($data))
    		{
    			$this->success('修改文章成功！','articlelist');
    		}	else {
    			$this->error('修改文章失败！', 'edit');
    		}
    		return;
    	}
    	$this->assign('articles',$articles);
        $cateres=db('cate')->select();
        $this->assign('cateres',$cateres);
    	return $this->fetch();
    }

	public function articlelist() 
	{
		$list = ArticleModel::paginate(100);
		$this->assign('list',$list);
		return $this->fetch();
	}

	public function del()	
	{
		$id = input('id');
		if(db('Article')->delete(input('id')))	{
			$this->success('删除文章成功!','Articlelist');
		}	else {
			$this->error('删除文章失败 ! ');
		}
	}
}